package com.zkw.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * Created by Administrator on 2016/4/28 0028.
 * 主要通过读取文件内容，写到byteBuffer里，然后再从ByteBuffer对象中获取数据，显示到控制台
 */
public class ByteBufferDemo {
    public static void readFile(String fileName){
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(fileName,"rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(48);
            int size = fileChannel.read(byteBuffer);
            while (size>0){
                //把byteBuffer从写模式转变为读模式
                byteBuffer.flip();
                Charset charset = Charset.forName("UTF-8");
                System.out.println(charset.newDecoder().decode(byteBuffer).toString());
                byteBuffer.clear();
                size = fileChannel.read(byteBuffer);
            }

            fileChannel.close();
            randomAccessFile.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
